package com.zsd.android.opengldemo.renderer;

import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import com.zsd.android.opengldemo.filter.CameraFilter;
import com.zsd.android.opengldemo.filter.ScreenFilter;
import com.zsd.android.opengldemo.view.widget.SkinView;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class SkinRenderer implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {

    private SkinView skinView;
    private SurfaceTexture surfaceTexture;
    private int[] mTextures;
    private float[] mtx = new float[16];
    private CameraFilter mCameraFilter;
    private ScreenFilter mScreenFilter;

    public SkinRenderer(SkinView skinView) {
        this.skinView = skinView;
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        //打开摄像头

        mTextures = new int[1];
        //offset 表示对mTextures中的第几个来进行处理，即下标，mTextures[0]
        GLES20.glGenTextures(mTextures.length, mTextures, 0);
        surfaceTexture = new SurfaceTexture(mTextures[0]);
        surfaceTexture.setOnFrameAvailableListener(this);
        //矩阵 ---> 摄像头的数据不会变形
        surfaceTexture.getTransformMatrix(mtx);
        mCameraFilter = new CameraFilter(skinView.getContext());
        mScreenFilter = new ScreenFilter(skinView.getContext());
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        mCameraFilter.onReady(width, height);
    }

    /**
     * 摄像头获取一帧数据会回调此方法
     * @param gl
     */
    @Override
    public void onDrawFrame(GL10 gl) {
        GLES20.glClearColor(0, 0, 0, 0);
        //执行清空
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        surfaceTexture.updateTexImage();
        int id = mCameraFilter.onDrawFrame(mTextures[0]);
        mScreenFilter.onDrawFrame(id);
    }

    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        skinView.requestRender();
    }
}
